package cn.wsn2018.tools.dao.impl;

import cn.wsn2018.tools.dao.UserDao;
import cn.wsn2018.tools.model.User;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.logging.Logger;

/**
 * Created by NZX on 2018/12/11.
 */
@Repository("userDao")
public class UserDaoImpl implements UserDao{
    private Logger logger = Logger.getLogger(UserDaoImpl.class.getName());
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public List<User> listAllUsers(String pageNum,String pageSize) {
        Query query = new Query();
        query.with(new Sort(Sort.Direction.DESC,"createTime"));
        int num = Integer.parseInt(pageNum);
        int size = Integer.parseInt(pageSize);
        query.skip((num-1)*size).limit(size);
        List<User> userList = mongoTemplate.find(query,User.class,"user");
        return userList;
    }

    @Override
    public List<User> listUsersByRole(String role,String pageNum,String pageSize) {
        Query query = new Query();
        query.addCriteria(Criteria.where("role").is(role));
        query.with(new Sort(Sort.Direction.DESC,"createTime"));
        int num = Integer.parseInt(pageNum);
        int size = Integer.parseInt(pageSize);
        query.skip((num-1)*size).limit(size);
        List<User> userList = mongoTemplate.find(query,User.class,"user");
        return userList;
    }

    @Override
    public User getUserByName(String username) {
        Query query = new Query();
        query.addCriteria(Criteria.where("username").is(username));
        User user = mongoTemplate.findOne(query,User.class,"user");
        return user;
    }

    /**
     * 插入用户
     * @param user
     * @return
     */
    @Override
    public boolean saveUser(User user) {
        JSONObject result = JSONObject.fromObject(mongoTemplate.insert(user,"user"));
        String id = result.optString("id");
        if(id!=null&&!"".equals(id)) {
            //logger.info(result.toString());
            return true;
        }
        else {
            return false;
        }
    }

    /**
     * 删除用户，dao成功返回{"deletedCount":1}
     * @param username
     * @return
     */
    @Override
    public boolean deleteUser(String username) {
        User user = new User();
        user.setUsername(username);
        Query query = new Query();
        query.addCriteria(Criteria.where("username").is(username));
        JSONObject result = JSONObject.fromObject(mongoTemplate.remove(query,User.class,"user"));
        String count = result.optString("deletedCount");
        if(count!=null&&"1".equals(count)){
            return true;
        }else {
            return false;
        }
    }

    /**
     * 修改用户  {"matchedCount":1,"modifiedCount":1,"modifiedCountAvailable":true,"upsertedId":null}
     * @param user
     * @return
     */
    @Override
    public boolean updateUser(String formerName,User user) {
        Query query = new Query();
        query.addCriteria(Criteria.where("username").is(formerName));
        Update update = new Update();
        update.set("username",user.getUsername()).set("password",user.getPassword()).set("role",user.getRole());
        JSONObject result = JSONObject.fromObject(mongoTemplate.upsert(query,update,"user"));
        String count = result.optString("modifiedCount");
        if(count!=null&&"1".equals(count)){
            return true;
        }else {
            return false;
        }
    }
}
